#include <QListView>
#include <QSizePolicy>
#include <QStringList>
#include <QSizePolicy>

#include <osg/MatrixTransform>
#include <osg/Vec3d>

#include "viewerWidget.h"
#include <osgQt/GraphicsWindowQt>
#include <config>


ViewerWidget::ViewerWidget() : QWidget()
{
	_view = new osgViewer::View;
	setThreadingModel(osgViewer::CompositeViewer::SingleThreaded);

	_viewerWidget = setViewWidget( createCamera(0,0,100,100));

	QGridLayout* layout = new QGridLayout();
	layout->setMargin(1);
	layout->addWidget(_viewerWidget);

	this->setLayout(layout);
	_viewerWidget->show();
	_viewerWidget->setParent(this);

	this->setMinimumHeight(200);
	this->setMinimumWidth(200);
	connect( &_timer, SIGNAL(timeout()), this, SLOT(update()) );
	_timer.start( 10 );
}

void ViewerWidget::paintEvent( QPaintEvent* event )
{
	frame();
}

osg::Camera* ViewerWidget::createCamera( int x, int y, int w, int h, const std::string& name/*=""*/, bool windowDecoration/*=false */ )
{
	osg::DisplaySettings* ds = osg::DisplaySettings::instance().get();
	osg::ref_ptr<osg::GraphicsContext::Traits> traits = new osg::GraphicsContext::Traits;
	traits->windowName = name;
	traits->windowDecoration = windowDecoration;
	traits->x = x;
	traits->y = y;
	traits->width = w;
	traits->height = h;
	traits->doubleBuffer = true;
	traits->alpha = ds->getMinimumNumAlphaBits();
	traits->stencil = ds->getMinimumNumStencilBits();
	traits->sampleBuffers = ds->getMultiSamples();
	traits->samples = ds->getNumMultiSamples();

	osg::ref_ptr<osg::Camera> camera = new osg::Camera;
	camera->setGraphicsContext( new osgQt::GraphicsWindowQt(traits.get()) );

	camera->setClearColor( osg::Vec4(0.2, 0.2, 0.6, 1.0) );
	camera->setViewport( new osg::Viewport(0, 0, traits->width, traits->height) );
	camera->setProjectionMatrixAsPerspective(
		30.0f, static_cast<double>(traits->width)/static_cast<double>(traits->height), 1.0f, 10000.0f );
	return camera.release();
}

QWidget* ViewerWidget::setViewWidget(osg::Camera* camera)
{

	_view->setCamera( camera );
	addView( _view );

	_view->addEventHandler(new osgGA::StateSetManipulator(_view->getCamera()->getOrCreateStateSet()));
	_view->addEventHandler( new osgViewer::StatsHandler );

	osgQt::GraphicsWindowQt* gw = dynamic_cast<osgQt::GraphicsWindowQt*>( camera->getGraphicsContext() );
	return gw ? gw->getGLWidget() : NULL;
}

bool ViewerWidget::setScene( osg::Node* scene )
{
	_view->setSceneData( scene );
	this->realize();
	return true;
}

osgViewer::View* ViewerWidget::getViewer()
{
	return _view;
}


